<?php

/**
 * @name CartController
 * @desc 控制器
 */
class CartController extends UserCommonController
{
    //购物车列表
    public function listAction(){
        $params = $this->post();

        $row = $params['pageSize'] ?? 1000;
        $page = $params['page'] ?? 1;

        $cond = ['c.user_id'=> $this->user_info['user_id'], 'sps.shop_id'=> $this->user_info['offline_shop_id']];
        $cartModel = CartModel::getSingleton();
        $list = $cartModel->db
            ->field('c.id as cart_id,c.buy_num, c.product_id, c.checked, c.spec_id, p.product_name, p.cover_img, ps.spec_name_full, ps.unit_money,sps.is_show,sps.shop_spec_stock as spec_stock,sps.id')
            ->alias('c')
            ->join(['product', 'p'], ['c.product_id'=> 'p.product_id'], 'left join')
            ->join(['product_specs', 'ps'], ['c.spec_id'=> 'ps.spec_id'], 'left join')
            ->join(['shop_product_specs', 'sps'], ['c.spec_id'=> 'sps.spec_id'], 'left join')
            ->where_c($cond)
            ->order('c.create_time desc')
            ->limit(($page - 1) * $row, $row)
            ->select();

        $total = $cartModel->db
            ->alias('c')
            ->join(['product', 'p'], ['c.product_id'=> 'p.product_id'], 'left join')
            ->join(['product_specs', 'ps'], ['c.spec_id'=> 'ps.spec_id'], 'left join')
            ->join(['shop_product_specs', 'sps'], ['c.spec_id'=> 'sps.spec_id'], 'inner join')
            ->where_c($cond)
            ->count();

        $totalMoney = 0;
        foreach($list as &$val){
            //总价
            $val['cart_unit_money'] = round($val['unit_money'] * $val['buy_num'], 2);
            $val['product_name_full'] = $val['product_name']. ' '. $val['spec_name_full'];
            if($val['checked'] == 1){
                $totalMoney += $val['cart_unit_money'];
            }
        }

        $data = [
            'total_money'  => $totalMoney,
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page),
            'pageNum'   => ceil($total/$row)
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //新购物车逻辑
    public function editAction(){
        $params = $this->post();

        $rule = [
            'spec_id'     => 'require|number',
            'selected_num'  => 'require|number|min:1'
        ];
        $msg = [
            'spec_id.require' => '必须选择商品',
            'spec_id.number'   => '商品ID不正确',
            'selected_num.require'   => '必须选择购买数量',
            'selected_num.number'   => '购买数量不正确',
            'selected_num.min'   => '购买数量最小为1'
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        //获取规格
        $shopProductSpecModel = ShopProductSpecsModel::getSingleton();
        $cartModel = CartModel::getSingleton();
        //商品详情页操作购物车
        if(isset($params['page']) && $params['page'] == 'product_detail'){
            $shopProductSpecDetail = $shopProductSpecModel->db
                ->alias('sps')
                ->field('sps.*, ps.spec_name_full,ps.unit_money,p.product_name')
                ->join(['product_specs', 'ps'], ['sps.spec_id'=> 'ps.spec_id'], 'left join')
                ->join(['product', 'p'], ['sps.product_id'=> 'p.product_id'], 'inner join')
                ->where_c(['sps.spec_id'  => $params['spec_id']])
                ->find();
            if($shopProductSpecDetail['shop_id'] != $this->user_info['offline_shop_id']){
                $this->ajaxReturn(400, '此商品店铺缺货，请联系店铺购买'.$shopProductSpecDetail['shop_id'].$this->user_info['offline_shop_id']);
            }
            $cartInfo = $cartModel->find([
                'user_id'   => $this->user_info['user_id'],
                'product_id'=> $shopProductSpecDetail['product_id'],
                'spec_id'=> $shopProductSpecDetail['spec_id']
            ]);
            //验证库存
            if($cartInfo){
                $total_buy_num = $cartInfo['buy_num'] + $params['selected_num'];
            }else {
                $total_buy_num = $params['selected_num'];
            }
            if($total_buy_num> $shopProductSpecDetail['shop_spec_stock']){
                $this->ajaxReturn(400, '无法继续添加购物车了');
            }
            if($cartInfo){
                $res = $cartModel->setInc([
                    'user_id'   => $this->user_info['user_id'],
                    'product_id'=> $shopProductSpecDetail['product_id'],
                    'spec_id'=> $shopProductSpecDetail['spec_id']
                ], 'buy_num', $params['selected_num']);
            }else {
                $res = $cartModel->add([
                    'user_id'    => $this->user_info['user_id'],
                    'spec_id'   => $shopProductSpecDetail['spec_id'],
                    'checked'   => 1,
                    'product_id'       => $shopProductSpecDetail['product_id'],
                    'buy_num'          => $params['selected_num'],
                ]);
            }
            if(!$res){
                $this->ajaxReturn(400, '添加失败', $cartModel->errMsg);
            }

            $shopProductSpecDetail['product_name_full'] = $shopProductSpecDetail['product_name']. ' '. $shopProductSpecDetail['spec_name_full'];
            $shopProductSpecDetail['spec_name_full'] = '规格：' . $shopProductSpecDetail['spec_name_full'];
            //返回规格商品信息
            $this->ajaxReturn(0, '添加成功', $shopProductSpecDetail);
        }else {
            $shopProductSpecDetail = $shopProductSpecModel->db
                ->alias('sps')
                ->field('sps.*, ps.spec_name_full,p.product_name')
                ->join(['product_specs', 'ps'], ['sps.spec_id'=> 'ps.spec_id'], 'left join')
                ->join(['cart', 'c'], ['sps.spec_id'=> 'c.spec_id'], 'inner join')
                ->join(['product', 'p'], ['sps.product_id'=> 'p.product_id'], 'inner join')
                ->where_c(['sps.spec_id'  => $params['spec_id'],'c.user_id'=> $this->user_info['user_id']])
                ->find();
            if($shopProductSpecDetail['shop_id'] != $this->user_info['offline_shop_id']){
                $this->ajaxReturn(400, '所属店铺异常');
            }
            if($params['selected_num']> $shopProductSpecDetail['shop_spec_stock']){
                //更新到最高库存
                $cartModel->update([
                    'user_id'   => $this->user_info['user_id'],
                    'product_id'=> $shopProductSpecDetail['product_id'],
                    'spec_id'=> $shopProductSpecDetail['spec_id']], ['buy_num'=> $shopProductSpecDetail['shop_spec_stock']]);
                $this->ajaxReturn(410, '库存不足', $shopProductSpecDetail['shop_spec_stock']);
            }
            $data['buy_num'] = $params['selected_num'];
            $data['update_time'] = time();
            if(isset($params['checked'])){
                $data['checked'] = $params['checked'];
            }
            if(!$cartModel->update([
                'user_id'   => $this->user_info['user_id'],
                'product_id'=> $shopProductSpecDetail['product_id'],
                'spec_id'=> $shopProductSpecDetail['spec_id']], $data)){
                $this->ajaxReturn(400, '操作失败');
            }
            $this->ajaxReturn(0 ,'操作成功');
        }

        return false;
    }

    //删除购物车商品
    public function delAction(){
        $params = $this->post();
        if(!isset($params['spec_id']) || !intval($params['spec_id'])){
            $this->ajaxReturn(400, '必须选择商品');
        }
        if(!CartModel::getSingleton()->delete(['user_id'=> $this->user_info['user_id'], 'spec_id'=> $params['spec_id']])){
            $this->ajaxReturn(400, '删除失败，请刷新重试');
        }
        $this->ajaxReturn(0, '已删除');
    }

    //全选，取消全选
    public function checkallAction(){
        $params = $this->post();
        if(!isset($params['checked'])){
            $this->ajaxReturn(400, '必须选择选中状态');
        }

        if(!CartModel::getSingleton()->update(['user_id'=> $this->user_info['user_id']], ['checked'=> $params['checked'], 'update_time'=> time()])){
            $this->ajaxReturn(400, '操作失败');
        }
        $this->ajaxReturn(0, '操作成功');
    }
}
